/*
 * T_Junction_Slave.c
 *
 * Created: 6/11/2013 8:30:53 PM
 *  Author: Crossfire
 */


#include <avr/io.h>
#include "Globals.h"
#include "T-Junction_Slave.h"
#include "T-Junction_1.h"
#include "T-Junction_2.h"
#include "I2C.h"

int main(void)
{
	void init();
    while(1)
    {
         while((TWSR & 0xF8)!= 0x60)  // Loop till correct acknoledgement have been received
         {
	         // Get acknowlegement, Enable TWI, Clear TWI interrupt flag
	         TWCR=(1<<TWEA)|(1<<TWEN)|(1<<TWINT);
	         while (!(TWCR & (1<<TWINT)))  // Wait for TWINT flag
	         {
		         get_Sensors1();
				 get_Sensors2();
		         set_State1();
		         set_State2();
				 	orByteA = 0;
				 	orByteB = 0;
				 	orByteC = 0;
				 	orByteD = 0;
		         set_Trafficlights1();
				 set_Trafficlights2();
				 PORTA = orByteA;
				 PORTB = orByteB;
				 PORTC = orByteC;
				 PORTD = orByteD;
		         set_Delay1();
				 set_Delay2();
	         }
         }
         parse_data_Tjunction();
    }
}

void init()
{
	DDRC = (1<<PC7) | (1<<PC6) | (1<<PC5) | (1<<PC4)
	| (1<<PC3) | (1<<PC2) | (1<<PC1) | (1<<PC0);

	PORTC &= ~((1<<PC7) | (1<<PC6) | (1<<PC5) | (1<<PC4)
	| (1<<PC3) | (1<<PC2) | (1<<PC1) | (1<<PC0));
	DDRB = 0x0F;
	DDRA = 0xC0;
	DDRD = 0xFC;
	PORTB = 0;
	//Prescale 64
	TCCR1B |= 0b00000011;
	_delay_ms(500);
	TCNT1 = 0;
	TWI_init_slave(); // Function to initilaize slave
	_mode = 1;
	_delay_ms(1000);
	PORTB = ~0;
}
